/*
 * @Description: 
 * @Author: Jimmy
 * @Date: 2023-07-23 10:16:54
 * @LastEditTime: 2023-07-23 10:56:33
 * @LastEditors:  
 */

import Schema, { Rules, Values } from "async-validator"
import { Context } from "koa"

/**
 * 
 * @param ctx   
 * @param rules 校验规则
 * @param flag  是否返回完整的校验结果
 * @returns 
 */
async function validate<T extends Values>(ctx: Context, rules: Rules, flag: Boolean = false): Promise<{ data: T, error: any }> {
    const validator = new Schema(rules);
    let data = getFormData(ctx)
    return validator.validate(data).then(() => {
        return {
            data: data as T,
            error: null
        }
    }).catch(err => {
        if (flag) {
            return {
                data: {} as T,
                error: err
            }
        }
        return {
            data: {} as T,
            error: err.errors[0].message
        }
    })
}

function getFormData(ctx: Context) {
    let data = null;
    switch (ctx.method) {
        case 'GET':
            data = JSON.parse(JSON.stringify(ctx.query)) || {}
            break;
        case 'POST':
            data = ctx.request.body || {};
            break;
        case 'PUT':
            data = ctx.request.body || {};
            break;
        case 'DELETE':
            data = JSON.parse(JSON.stringify(ctx.query)) || {}
            break;
    }
    return data
}

export default validate